package cn.lanqiao.bigDate.web.controller;


import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * jsr303工具
 */
public class ValidatorUtil {

    private ValidatorUtil(){}

    private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

    /**
     *
     * @param obj
     * @return
     */
    public static Map validate(Object obj){
        //创建一个map存储校验的结果
        Map<Object, Object> resultMap = new HashMap<>();
        //获取验证器
        Validator validator = factory.getValidator();
        //校验数据
        Set<ConstraintViolation<Object>> validate = validator.validate(obj);
        //校验通过
        if (validate.isEmpty()){
            //返回一个空的map
            return Collections.EMPTY_MAP;
        }
        for (ConstraintViolation<Object> result : validate) {
            resultMap.put(result.getPropertyPath().toString(),result.getMessage());
        }
        return resultMap;
    }
}
